package com.example.nowcodercommunity.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
public class DruidDataSourceConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDatasource(){
        return new DruidDataSource();
    }

    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
        HashMap<String,String> initParameters = new HashMap<>();

        //这里的两个Key是固定的，不能乱写，用于配置访问账号和密码
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","123456");

        //再就是配置允许访问的IP地址，这里写的是本机允许访问，但正常是规定某个IP可以访问而不是服务器来访问
        initParameters.put("allow","localhost");

        bean.setInitParameters(initParameters);
        return bean;
    }
}
